package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
)

func main() {
	ln, err := net.Listen("tcp", ":6010")
	if err != nil {
		panic(err)
	}
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Fatal("get client connection error: ", err)
		}
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	data, err := bufio.NewReader(conn).ReadString('\n')
	if err != nil {
		log.Fatal("get client data error: ", err)
	}
	if checkFileIsExist("ip.txt") {
		f, err := os.OpenFile("ip.txt", os.O_WRONLY, 0644)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		defer f.Close()
		n, _ := f.Seek(0, os.SEEK_END)
		_, err = f.WriteAt([]byte(data), n)

	} else {
		f, err := os.Create("ip.txt")
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		defer f.Close()
		f.WriteString(data)
	}
	conn.Close()
}

func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}
